package main

import (
	"bufio"
	"fmt"
	"io"
	"log"
	"net"
)

const serverAddr = "192.168.1.43:11344"

func main() {
	send(getData())
}

func getData() string {
	header := "GET /index HTTP/1.1\r\n" +
		"Host: 192.168.1.43:8002\r\n" +
		"Accept: text/html, text/plain\r\n" +
		"Accept-Encoding: gzip, compress\r\n" +
		"\r\n"

	body := "HTTP/1.1 200 OK\r\n" +
		"Content-Type: application/json; charset=utf-8\r\n" +
		"Date: Sat, 10 Sep 2022 11:45:55 GMT\r\n" +
		"Content-Length: 13\r\n" +
		"\r\n" +
		"{\"data\":\"13822122323\"}\r\n" +
		"\r\n"

	headerLen := len(header)
	bodyLen := len(header) + len(body)

	return fmt.Sprintf("RESPMOD icap://192.168.1.43:11344/resq ICAP/1.0\r\n"+
		"Host: 192.168.1.43:11344\r\n"+
		"Encapsulated: req-hdr=0, res-hdr=%d, res-body=%d\r\n\r\n%s%s",
		headerLen,
		bodyLen,
		header,
		body)
}

func send(body string) {
	conn, err := net.Dial("tcp", serverAddr)
	if err != nil {
		log.Panic(err)
	}

	defer conn.Close()

	io.WriteString(conn, body)
	reader := bufio.NewReader(conn)
	var buf [1024]byte
	for {
		n, err := reader.Read(buf[:])
		if err == io.EOF {
			break
		}
		if err != nil {
			fmt.Println("read from client failed, err:", err)
			break
		}
		recvStr := string(buf[:n])
		fmt.Println(string(recvStr[:n]))
	}
}
